import React, { useState } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { Button, Radio, message, Spin, Modal, QRCode, Progress } from 'antd';
import { ArrowLeftOutlined, SafetyOutlined } from '@ant-design/icons';
import { orderAPI } from '../../services/api';
import { removeFromCart } from '../../utils/storage';
import { usePoints as deductPoints } from '../../utils/points';
import './Payment.css';

const Payment = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [paymentMethod, setPaymentMethod] = useState('alipay');
  const [loading, setLoading] = useState(false);
  const [showQRCode, setShowQRCode] = useState(false);
  const [paymentProgress, setPaymentProgress] = useState(0);
  const [paymentStatus, setPaymentStatus] = useState('waiting'); // waiting, scanning, success
  
  const orderData = location.state?.orderData;
  const orderId = location.state?.orderId;

  // 从订单数据中获取支付方式
  React.useEffect(() => {
    if (orderData?.paymentMethod) {
      setPaymentMethod(orderData.paymentMethod);
    }
  }, [orderData]);

  if (!orderData || !orderId) {
    return (
      <div className="payment-error">
        <div className="error-content">
          <h3>订单信息丢失</h3>
          <p>请重新下单</p>
          <Button type="primary" onClick={() => navigate('/app')}>
            返回首页
          </Button>
        </div>
      </div>
    );
  }

  const getPaymentMethodName = () => {
    const methods = {
      alipay: '支付宝',
      wechat: '微信支付',
      bankcard: '银行卡支付'
    };
    return methods[paymentMethod] || '支付宝';
  };

  const handlePayment = () => {
    setShowQRCode(true);
    setPaymentStatus('waiting');
    setPaymentProgress(0);
    
    // 模拟扫码支付进度
    simulatePaymentProcess();
  };

  const simulatePaymentProcess = () => {
    let progress = 0;
    const interval = setInterval(() => {
      progress += 20;
      setPaymentProgress(progress);
      
      if (progress === 40) {
        setPaymentStatus('scanning');
      }
      
      if (progress >= 100) {
        clearInterval(interval);
        setPaymentStatus('success');
        setTimeout(() => {
          completePayment();
        }, 1000);
      }
    }, 800);
  };

  const completePayment = async () => {
    setLoading(true);
    
    try {
      // 更新订单状态为已支付
      const response = await orderAPI.updateOrderStatus(orderId, 'paid');
      
      if (response.success) {
        // 如果使用了积分，扣除积分
        if (orderData.usePoints && orderData.pointsDiscount > 0) {
          const pointsToUse = Math.ceil(orderData.pointsDiscount / 0.01);
          deductPoints(pointsToUse, `订单${orderData.orderNo}积分抵扣`);
        }
        
        // 如果是从购物车下单，需要清空购物车中对应的商品
        if (orderData.fromCart) {
          orderData.products.forEach(product => {
            removeFromCart(product.cartId);
          });
        }

        message.success('支付成功');
        setShowQRCode(false);
        navigate('/app/payment/success', { 
          state: { 
            orderId,
            orderNo: orderData.orderNo,
            amount: orderData.totalAmount,
            paymentMethod
          } 
        });
      } else {
        message.error('支付失败');
        setShowQRCode(false);
      }
    } catch (error) {
      message.error('支付失败，请重试');
      setShowQRCode(false);
    } finally {
      setLoading(false);
    }
  };

  const cancelPayment = () => {
    setShowQRCode(false);
    setPaymentStatus('waiting');
    setPaymentProgress(0);
  };     

  return (
    <div className="payment-page">
      {/* 头部导航 */}
      <div className="payment-header">
        <Button 
          type="text" 
          icon={<ArrowLeftOutlined />}
          onClick={() => navigate(-1)}
        />
        <span className="header-title">确认支付</span>
      </div>

      {/* 订单信息 */}
      <div className="payment-order-info">
        <div className="order-summary">
          <div className="order-no">订单号：{orderData.orderNo}</div>
          <div className="order-amount">
            <span className="amount-label">应付金额</span>
            <span className="amount-value">¥{orderData.totalAmount.toFixed(2)}</span>
          </div>
        </div>
        
        <div className="order-details">
          <div className="detail-item">
            <span>商品总额</span>
            <span>¥{orderData.originalAmount.toFixed(2)}</span>
          </div>
          <div className="detail-item">
            <span>运费</span>
            <span>免运费</span>
          </div>
          {orderData.pointsDiscount > 0 && (
            <div className="detail-item discount">
              <span>积分抵扣</span>
              <span>-¥{orderData.pointsDiscount.toFixed(2)}</span>
            </div>
          )}
        </div>
      </div>

      {/* 支付方式显示 */}
      <div className="payment-method-display">
        <div className="section-title">支付方式</div>
        <div className="selected-payment-method">
          <div className="payment-method-info">
            <div className="payment-icon">
              {paymentMethod === 'alipay' && <img src="https://cdn4.iconfinder.com/data/icons/logos-and-brands/512/13_Alipay_logo_logos-1024.png" alt="支付宝" style={{width: '26px', height: '26px', marginLeft: '5px'}} />}
              {paymentMethod === 'wechat' && <img src="https://cdn3.iconfinder.com/data/icons/social-messaging-ui-color-shapes-2-free/128/social-wechat-circle-512.png" alt="微信支付" style={{width: '26px', height: '26px', marginLeft: '5px'}} />}
              {paymentMethod === 'bankcard' && <img src="https://cdn1.iconfinder.com/data/icons/business-547/50/81-512.png" alt="银联支付" style={{width: '26px', height: '26px', marginLeft: '5px'}} />}
            </div>
            <span className="payment-name">{getPaymentMethodName()}</span>
          </div>
        </div>
      </div>

      {/* 安全提示 */}
      <div className="security-tip">
        <SafetyOutlined style={{ color: '#52c41a', marginRight: '8px' }} />
        <span>安全支付，您的资金将受到银行级安全保障</span>
      </div>

      {/* 支付按钮 */}
      <div className="payment-footer">
        <div className="payment-amount">
          应付：<span className="final-amount">¥{orderData.totalAmount.toFixed(2)}</span>
        </div>
        <Button 
          type="primary"
          size="large"
          onClick={handlePayment}
          loading={loading}
          className="pay-btn"
        >
          确认支付¥{orderData.totalAmount.toFixed(2)}
        </Button>
      </div>

      {/* 二维码支付弹窗 */}
      <Modal
        title={`${getPaymentMethodName()}扫码支付`}
        open={showQRCode}
        onCancel={cancelPayment}
        footer={null}
        width={350}
        centered
        className="payment-qr-modal"
      >
        <div className="qr-payment-content">
          <div className="qr-amount">
            ¥{orderData.totalAmount.toFixed(2)}
          </div>
          
          <div className="qr-code-container">
            <QRCode
              value={`payment:${orderId}:${orderData.totalAmount}:${paymentMethod}`}
              size={200}
              style={{
                marginBottom: 16,
                opacity: paymentStatus === 'success' ? 0.5 : 1
              }}
            />
            
            {paymentStatus === 'success' && (
              <div className="payment-success-overlay">
                <div className="success-icon">✅</div>
                <div className="success-text">支付成功</div>
              </div>
            )}
          </div>

          <div className="payment-progress-section">
            <Progress 
              percent={paymentProgress} 
              showInfo={false}
              strokeColor={{
                '0%': '#108ee9',
                '100%': '#87d068',
              }}
            />
            
            <div className="payment-status-text">
              {paymentStatus === 'waiting' && '请使用手机扫描二维码'}
              {paymentStatus === 'scanning' && '正在支付...'}
              {paymentStatus === 'success' && '支付成功！正在跳转...'}
            </div>
          </div>

          <div className="payment-tips">
            <div className="tip-item">
              <span className="tip-icon">📱</span>
              <span>打开{getPaymentMethodName()}APP扫描二维码</span>
            </div>
            <div className="tip-item">
              <span className="tip-icon">🔐</span>
              <span>确认支付金额后完成付款</span>
            </div>
          </div>

          <Button 
            block 
            onClick={cancelPayment}
            style={{ marginTop: '16px' }}
          >
            取消支付
          </Button>
        </div>
      </Modal>

      {/* 支付处理中遮罩 */}
      {loading && (
        <div className="payment-loading-overlay">
          <div className="loading-content">
            <Spin size="large" />
            <div className="loading-text">正在处理支付...</div>
            <div className="loading-tip">请不要关闭页面</div>
          </div>
        </div>
      )}
    </div>
  );
};

export default Payment; 